package com.wenruo.funycollecte.util;

import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;

public class JsonRequest<T> extends Request<T> {
    
	private final Gson mGson;
    private final Class<T> mClazz;
    private final Listener<T> mListener;
    private final Map<String, String> mParams;

    public JsonRequest(int method,
                       String url,
                       Map<String, String> params,
                       Class<T> clazz,
                       Listener<T> listener,
                       ErrorListener errorListener) {
        super(method, url, errorListener);
        mParams = params;
        mClazz = clazz;
        mListener = listener;
        mGson = new Gson();
    }

    @Override
    protected void deliverResponse(T response) {
        mListener.onResponse(response);
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            String json = new String(response.data);
            return Response.success(mGson.fromJson(json, mClazz), HttpHeaderParser.parseCacheHeaders(response));
        } catch (JsonSyntaxException e) {
            return Response.error(new ParseError(e));
        }
    }
    
    @Override
	protected Map<String, String> getParams() throws AuthFailureError {
		return mParams;
	}
    
}